<!-- AI页面 -->
<template>
  <div @click="dialogVisible = true" class="ai">
    <svg
      t="1739152579553"
      class="icon"
      viewBox="0 0 1024 1024"
      version="1.1"
      xmlns="http://www.w3.org/2000/svg"
      p-id="1515"
      width="60"
      height="60"
    >
      <path
        d="M501.824 32C303.552 32 141.504 176.992 141.504 357.76c0 23.712 2.816 47.104 8.32 69.856l-51.008 114.208a32 32 0 0 0 24.704 44.736c54.272 7.744 76.672 31.168 76.672 77.312v111.552a64 64 0 0 0 64 64h20.704a64 64 0 0 1 64 64V960a32 32 0 0 0 32 32h345.6a32 32 0 0 0 0-64h-313.6v-24.608a128 128 0 0 0-128-128h-20.736v-111.552c0-65.664-32.192-110.688-91.2-131.136l39.872-89.28a31.968 31.968 0 0 0 1.568-21.792 233.088 233.088 0 0 1-8.896-63.904c0-143.712 131.936-261.76 296.32-261.76s296.32 118.016 296.32 261.76a32 32 0 0 0 64 0C862.144 176.992 700.064 32 501.824 32zM904 448a32 32 0 0 0-32 32v360a32 32 0 0 0 64 0V480a32 32 0 0 0-32-32z"
        p-id="1516"
        fill="#ff0000"
      ></path>
      <path
        d="M673.888 466.656c-11.744-25.568-48.416-24.64-58.816 1.536l-132.8 333.76a32 32 0 0 0 59.488 23.68l32.608-81.92c0.576 0.032 1.088 0.32 1.664 0.32h154.848l38.176 83.104a31.968 31.968 0 1 0 58.144-26.72l-153.312-333.76zM599.68 680l47.264-118.72 54.528 118.72H599.68z"
        p-id="1517"
        fill="#ff0000"
      ></path>
    </svg>
  </div>

  <el-dialog v-model="dialogVisible" title="AI智能助手" width="800">
    <div class="chat-box" ref="chatBox">
      <div
        v-for="(msg, index) in messages"
        :key="index"
        :class="msg.type === 'user' ? 'message1' : 'message'"
      >
        <div v-if="msg.type === 'user'" class="user-message">
          <img :src="avatar" alt="User" class="avatar" />
          <div class="message-content user-message-content">
            {{ msg.content }}
          </div>
        </div>
        <div v-if="msg.type === 'bot'" class="bot-message">
          <img :src="avatar_bot" alt="Bot" class="avatar" />
          <div
            class="message-content bot-message-content"
            v-html="msg.content"
          ></div>
        </div>
      </div>
    </div>

    <template #footer>
      <div class="dialog-footer">
        <div class="input-area">
          <el-input
            v-model="input"
            placeholder="请输入您的问题..."
            @keyup.enter="sendMessage"
            class="input-field"
            :style="{ maxWidth: 'calc(100% - 100px)' }"
          ></el-input>
          <el-button type="primary" @click="sendMessage">发送</el-button>
        </div>
      </div>
    </template>
  </el-dialog>
</template>
<script setup>
import OpenAI from "openai";
import robot from "@/assets/机器人.svg";
import user from "@/assets/男军人.svg";
const dialogVisible = ref(false);
const input = ref("");
const messages = ref([
  {
    type: "bot",
    content: "你好，我是智能助手，有什么问题可以问我吗？",
  },
]);
const avatar = user;
const avatar_bot = robot;
const chatBox = ref(null);

const client = new OpenAI({
  apiKey: "sk-8b6840c44b4c4ac58242058f7003106f",
  baseURL: "https://dashscope.aliyuncs.com/compatible-mode/v1",
  dangerouslyAllowBrowser: true,
});

async function chat() {
  try {
    const stream = await client.chat.completions.create({
      model: "deepseek-r1", // 此处以 deepseek-r1 为例，可按需更换模型名称
      messages: [{ role: "user", content: input.value }],
      stream: true,
    });
    console.log(stream);
    messages.value.push({
      type: "bot",
      content: "",
    });
    var first = true;
    var first2 = true;
    for await (const chunk of stream) {
      //   // 获取思考过程
      const reasoningChunk = chunk.choices[0]?.delta?.reasoning_content || "";
      //   // 获取回复
      const answerChunk = chunk.choices[0]?.delta?.content || "";
      //   console.log(reasoningChunk);

      //   // 如果思考过程不为空，则打印思考过程
      if (reasoningChunk && first2) {
        messages.value[
          messages.value.length - 1
        ].content += `<h2>思考过程</h2>`;
        messages.value[messages.value.length - 1].content += reasoningChunk;
        first2 = false;
      }
      // 如果回复不为空，则打印回复。回复一般会在思考过程结束后返回
      else if (answerChunk && first) {
        messages.value[
          messages.value.length - 1
        ].content += `<h2>最终结果</h2>`;
        messages.value[messages.value.length - 1].content += answerChunk;
        first = false;
      } else if (answerChunk) {
        messages.value[messages.value.length - 1].content += answerChunk;
      } else if (reasoningChunk) {
        messages.value[messages.value.length - 1].content += reasoningChunk;
      }
      scrollToBottom();
    }
    // console.log(`\n完整思考过程：${reasoningContent}`);
    // console.log(`完整的回复：${answerContent}`);
  } catch (error) {
    console.error("发生错误:", error);
  }
}

/**提问 */
const sendMessage = () => {
  if (input.value.trim() === "") return;
  messages.value.push({ type: "user", content: input.value });
  chat();
  input.value = "";
};
/**回到底部 */
const scrollToBottom = () => {
  nextTick(() => {
    chatBox.value.scrollTop = chatBox.value.scrollHeight;
  });
};
</script>
<style lang="scss" scoped>
.ai {
  position: fixed;
  right: 20px;
  bottom: 30%;
  cursor: pointer;
  width: 60px;
}
.chat-box {
  height: 50vh;
  overflow-y: auto;
  padding: 10px;
  border-bottom: 1px solid #dcdfe6;
}
.input-area {
  display: flex;
  align-items: center;
  margin-top: 10px;
}
.message {
  margin: 10px 0;
  display: flex;
  align-items: center;
}
.message1 {
  margin: 10px 0;
  display: flex;
  align-items: center;
  justify-content: flex-end;
}
.user-message {
  margin-top: 2px;
  display: flex;
  align-items: center;
  /**反转 */
  flex-direction: row-reverse;
  justify-content: flex-end;
}
.bot-message {
  margin-top: 2px;
  display: flex;
  align-items: center;
}
.avatar {
  border-radius: 50%;
  margin-right: 10px;
  width: 50px;
  height: 50px;
}
.input-field {
  flex: 1;
  margin-right: 10px;
  max-width: calc(100% - 100px);
}
.message-content {
  max-width: 100%; /* 确保消息内容框不超过聊天框宽度 */
  background-color: #f0f0f0; /* 随意选择背景颜色 */
  border-radius: 5px; /* 圆角 */
  padding: 10px; /* 内边距 */
  overflow-wrap: break-word; /* 使长文本换行 */
  white-space: normal; /* 允许文本在标签内换行 */
  word-wrap: break-word; /* 兼容旧版浏览器 */
}
.user-message-content {
  background-color: #d1e7dd; /* 用户消息的背景颜色 */
}
.bot-message-content {
  background-color: #cfe2ff; /* 机器人消息的背景颜色 */
}
</style>
